package com.szgd.controller.vehicle;

import com.szgd.controller.BaseController;
import com.szgd.controller.personnel.PersonnelInfoController;
import com.szgd.service.vehicle.VehicleService;
import com.szgd.util.Constant;
import com.szgd.util.ExcelUtil;
import com.szgd.util.PropertiesUtil;
import com.szgd.util.TimeUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value = "/vehicle")
public class VehicleController extends BaseController {
    @Autowired
    VehicleService vehicleService;

    private static Logger logger = Logger.getLogger(VehicleController.class);

    @RequestMapping(value = "toVehicleInfoList", method = RequestMethod.GET)
    public String toVehicleInfoList() {
        return "/vehicle/vehicleInfo/vehicleInfoList";
    }

    @RequestMapping(value = "toVehicleInfoView", method = RequestMethod.GET)
    public ModelAndView toVehicleInfoView(HttpServletRequest request, HttpSession session)
    {
        ModelAndView mv = getModelAndView(request,session,"/vehicle/vehicleInfo/vehicleInfoView");
        String id = mv.getModelMap().get("id")== null?"":mv.getModelMap().get("id").toString().replace("null","");;
        if (id.length() > 0)//修改
        {
            Map<String, Object> vehicleInfoMap = vehicleService.getVehicleInfo(id);
            mv.addObject("vehicleInfo",vehicleInfoMap);
        }
        return mv;
    }

    @RequestMapping(value = "toVehicleInfoForm", method = RequestMethod.GET)
    public ModelAndView toVehicleInfoForm(HttpServletRequest request, HttpSession session)
    {
        ModelAndView mv = getModelAndView(request,session,"/vehicle/vehicleInfo/vehicleInfoForm");
        String id = mv.getModelMap().get("id")== null?"":mv.getModelMap().get("id").toString().replace("null","");;
        if (id.length() > 0)//修改
        {
            Map<String, Object> vehicleInfoMap = vehicleService.getVehicleInfo(id);
            mv.addObject("vehicleInfo",vehicleInfoMap);
        }
        return mv;
    }

    @RequestMapping(value = "/getVehicleInfoList", method = RequestMethod.GET)
    public void  getVehicleInfoList(HttpServletResponse response,HttpServletRequest request){
        Map<String, Object> paramMap = getMapParams(request);
        List<Map<String, Object>> dataList = vehicleService.getVehicleInfoList(paramMap);
        outTableJSONDataCommon(response, dataList);
    }

    @RequestMapping(value = "/deleteVehicleInfo")
    @ResponseBody
    public Map<String,Object> deleteVehicleInfo(@RequestBody HashMap<String, Object> paramMap, HttpServletRequest request, HttpServletResponse response) {
        try{
            paramMap.put("uploader",this.getLoginId(request.getSession()));
            vehicleService.deleteVehicleInfo(paramMap);

            String message = "车辆信息删除成功！";
            return getSuccMap(message);
        }catch (Exception e)
        {
            e.printStackTrace();
            logger.error("车辆信息删除失败："+e.getMessage());
            return getSuccMap("车辆信息删除失败："+e.getMessage());
        }
    }

    @RequestMapping(value = "/saveVehicleInfo")
    @ResponseBody
    public Map<String,Object> saveVehicleInfo(@RequestBody HashMap<String, Object> paramMap,HttpServletRequest request,HttpServletResponse response) {
        String id = paramMap.get("id")== null?"":paramMap.get("id").toString().replace("null","");
        String message = "";
        try {
            if (id.length() == 0)//新增
            {
                paramMap.put("id",null);
                Map<String,Object> res = vehicleService.getVehicleInfo(paramMap);
                if(res != null && res.size() > 0){
                    logger.error("车辆新增失败：已存在该车牌号的车辆");
                    return getErrorMap("车辆新增失败：已存在该车牌号的车辆");
                }
                paramMap.put("creator",this.getLoginId(request.getSession()));
                vehicleService.insertVehicleInfo(paramMap);
                message = "车辆信息新增成功！";
            } else {
                paramMap.put("uploader",this.getLoginId(request.getSession()));
                vehicleService.updateVehicleInfo(paramMap);
                message = "车辆信息保存成功！";
            }
            return getSuccMap(message);
        }catch(Exception e){
            e.printStackTrace();
            logger.error("车辆信息保存失败："+e.getMessage());
            return getSuccMap("车辆信息保存失败："+e.getMessage());
        }
    }

    @ResponseBody
    @RequestMapping(value = "/batchUploadVehicleInfo", method = {RequestMethod.GET, RequestMethod.POST})
    public void batchUploadVehicleInfo(HttpServletRequest request, HttpServletResponse response) throws Exception {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        long startTime = System.currentTimeMillis();
        InputStream in = null;
        List<List<Object>> listob = null;
        MultipartFile file = multipartRequest.getFile("file");
        if (file.isEmpty()) {
            throw new Exception("文件不存在！");
        }
        in = file.getInputStream();
        PrintWriter out = null;
        response.setCharacterEncoding("UTF-8");  //防止ajax接受到的中文信息乱码
        response.setHeader("Content-type", "text/html;charset=UTF-8");   //跟上面同时使用可解决乱码问题
        out = response.getWriter();
        try {
            Map<String, String> fieldMapping = vehicleService.getFieldMap();
            List<Map<String, Object>> dataList = ExcelUtil.getListByExcel(in, file.getOriginalFilename(), fieldMapping, false);
            String batchNo = TimeUtil.formatDate(Calendar.getInstance().getTime(), "yyyyMMddhhmmss");
            Map<String, Object> resultMap = vehicleService.batchImportVehicleInfo(dataList, this.getLoginId(request.getSession()), batchNo);

            long endTime = System.currentTimeMillis();
            List<Map<String, Object>> successList = (List<Map<String, Object>>) resultMap.get(Constant.IMPORT_HE_SUCCESS);
            List<Map<String, Object>> ignoreList = (List<Map<String, Object>>) resultMap.get(Constant.IMPORT_HE_IGNORE);
            List<Map<String, Object>> failedList = (List<Map<String, Object>>) resultMap.get(Constant.IMPORT_HE_FAILED);
            List<Map<String, Object>> updatedList = (List<Map<String, Object>>) resultMap.get(Constant.IMPORT_HE_UPDATED);
            String errorHtml = failedList.size() + "条";

            if (failedList.size() > 0) {
                //生成失败记录文件
                String fileName = "车辆列表" + batchNo + ".xls";
                String filePath = PropertiesUtil.get("batchImportErrorPath");
                String realPath = request.getServletContext().getRealPath(filePath);
                filePath = filePath.replace("\\", "/");
                File f = new File(realPath);
                if (!f.exists()) {
                    f.mkdirs();
                }
                realPath = realPath + File.separator + fileName;
                exportExcelByTemplate(fieldMapping,failedList, realPath,"车辆信息批量导入模版.xls");
                String downloadPath = filePath + "/" + URLEncoder.encode(fileName,"UTF-8");
                errorHtml = "<a href='#WEBROOT#/downloadErrorRecord?path=" + downloadPath + "'>" + failedList.size() + "条（点击查看失败原因）</a>";
            }
            out.print("本次导入共处理" + dataList.size() + "条数据[新增：" + successList.size() + "条，更新："
                    + updatedList.size() + "条，<font color='red'>失败：" + errorHtml
                    + "</font>]，耗时： "
                    + (endTime - startTime) / 1000 + "秒！");
        } catch (Exception e) {
            out.print("文件导入失败！");
            logger.error(e.getMessage());
        }
        out.flush();
        out.close();
    }


}
